﻿App.define('signalr', function() {
	var signalr = {},
		hubs = ['defaultHub', 'gameHub'],
		stopDisconnectedEvent = false;
	try {
		signalr.ping = App.emptyFn;

		signalr.getHub = function(hub) {
			return $.connection[hub];
		};

		signalr.client = function(par) {
			signalr.getHub(par.hub).on(par.action, par.fn);
		};

		signalr.server = function(par) {
			var fn = signalr.getHub(par.hub).server[par.action];
			if (App.isUndefined(par.data)) {
				return fn();
			}
			return fn(par.data);
		};

		signalr.start = function () {
			return $.connection.hub.start();
		};

		signalr.stop = function() {
			$.connection.hub.stop();
		};

		signalr.reset = function() {
			stopDisconnectedEvent = true;
			signalr.stop();
		};

		$.each(hubs, function(i, item) {
			signalr.client({
				hub: item,
				action: 'Pong',
				fn: App.emptyFn
			});
		});

		signalr.ping = function(data) {
			signalr.server({
				hub: 'defaultHub',
				action: 'ping',
				data: data
			});
		};

		$.connection.hub.disconnected(function () {
			if (stopDisconnectedEvent) {
				stopDisconnectedEvent = false;
				return;
			}

			var i = 0, val = '', $body = $(document.body);
			var interval = setInterval(function() {
				i += 5;
				val = 'grayscale({0}%)'.replace('{0}', i);

				$body.css({
					'-webkit-filter': val,
					'-moz-filter': val,
					filter: val
				});

				if (i == 100) {
					clearInterval(interval);
					$("#disconnectPopup").click();
				}
			}, 50);
		});

		$(window).bind('beforeunload', function (evt) {
			if ($.connection.hub.state === $.connection.connectionState.disconnected) return;

			var m = Localization.LogoutConfirmation;
			App.isUndefined(evt) && (evt = window.event);
			evt && (evt.returnValue = m);

			return m;
		});

	} catch (e) {
		console.error('signalr.module.js', e);
	}

	return signalr;
});